package upload

import (
	"context"
	"net/http"

	"github.com/blog-zero/api/admin/internal/common/errorx"
	"github.com/blog-zero/api/admin/internal/svc"
	"github.com/blog-zero/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UploadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewUploadFileLogic(r *http.Request, ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileLogic {
	return &UploadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *UploadFileLogic) UploadFile() (*types.UploadFileResp, error) {
	_, file, err1 := l.r.FormFile("file")
	ContentType := l.r.PostFormValue("contentType")
	if err1 != nil {
		logc.Errorf(l.ctx, "获取文件失败,异常:%s", err1.Error())
		return nil, errorx.NewDefaultError("获取文件失败")
	}
	resp, err2 := l.svcCtx.Minio.UploadFile(l.r.Context(), file, ContentType)

	if err2 != nil {
		logc.Errorf(l.ctx, "上传minio失败,异常:%s", err2.Error())
		return nil, errorx.NewDefaultError("上传minio失败")
	}

	return &types.UploadFileResp{
		Code:    "000000",
		Message: "上传图片成功",
		Data:    resp,
	}, nil
}
